package redis

import (
	"encoding/json"
	"log"
	"time"

	"github.com/go-redis/redis/v7"
)

type Client struct {
	*redis.Client
}

func (this *Client) Ping() *Client {
	_, err := this.Client.Ping().Result()
	if err != nil {
		log.Println("[错误]", "Redis连接失败:", err.Error())
	} else {
		log.Println("[信息]", "Redis连接成功...")
	}
	return this
}

//SetCache 设置缓存,需要配合gf框架使用
//@key,redis的key,推荐使用url+token信息
//@fn,生成数据的方法,如果不需要数量,则返回-1
//@expiration,有效时间
func (this *Client) SetCache(key string, fn func() (interface{}, int64, error), expiration time.Duration) Info {
	s, err := this.Get(key).Result()
	if err != nil && err.Error() != redis.Nil.Error() {
		return newInfoErr(err)
	} else if err != nil {
		val, co, err := fn()
		if err != nil {
			return newInfoErr(err)
		}
		data := Info{Data: val, Count: co}
		bs, err := json.Marshal(data)
		if err != nil {
			return newInfoErr(err)
		}
		if err := this.Set(key, string(bs), expiration).Err(); err != nil {
			return newInfoErr(err)
		}
		return data
	}
	data := Info{}
	if err := json.Unmarshal([]byte(s), &data); err != nil {
		return newInfoErr(err)
	}
	return data
}
